﻿using AmuTools;
using app.Api;
using app.Common.recommendUtil;
using app.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;

namespace app.Api
{
    public class ApiDemand : ApiBase
    {
        public ApiDemand(Controller ctx) : base(ctx) { }

        string create_time { get { return GetStringParam(new ReqStringParamOption { Name = "create_time" }); } }
        string begin_time { get { return GetStringParam(new ReqStringParamOption { Name = "demand_beginDate" }); } }
        string end_time { get { return GetStringParam(new ReqStringParamOption { Name = "demand_endDate" }); } }

        public void Do(string action)
        {
            switch(action)
            {
                case "page":
                    {
                        // condition 条件拼接
                        string name = GetStringParam(new ReqStringParamOption { Name = "name", Level = REQPARAMLEVEL.FREE });
                        string number = GetStringParam(new ReqStringParamOption { Name = "number", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        cd.And("member_id='{0}'", UserCode);
                        if (req_status != 6)
                        {
                            cd.And("status='{0}'", req_status);
                        }
                        if (name != "")
                        {
                            cd.And("title like '%{0}%'", name);
                        }
                        if (number != "")
                        {
                            cd.And("number like '%{0}%'", number);
                        }
                        // orderby 排序拼接
                        Ob ob = new Ob();
                        ob.Desc("create_time");
                        if (req_excel)
                        {
                            DataTable dt = GetSqlResult<DemandItem>(cd.Render(), ob.Render()).FirstTable;
                            ResponseExcel(dt, DemandItem.ExcelColumns, DemandItem.ExcelColumnsHandle);
                        }
                        else
                        {
                            ResponseJson(GetPageResult<DemandItem>(cd.Render(), ob.Render()));
                        }
                        return;
                    }
                case "get":
                    {
                        DemandItem demand = G.DB.GetById<DemandItem>(req_id);
                        // 显示条件：是验证过的服务机构 或者是企业自己 或者是公开
                        if (demand.safety_grade == 0 || demand.member_id == UserCode
                            || ((ROLE_TYPES)UserRole == ROLE_TYPES.SERVICE && G.DB.GetById<Member>(UserCode).status == 2))
                        {
                            demand.view_times++;
                            G.DB.Update<DemandItem>(demand);
                        }
                        else
                        {
                            demand = null;
                        }
                        ResponseJson(new ObjectResult { data = demand });
                        return;
                    }
            }

            CheckPermission(IDENTITY.MEMBER);
            switch (action)
            {
                case "post":
                    {
                        DemandItem demand = null;
                        if (FreeValue.GetValue("check.open_check", "1") == "1")
                        {
                            demand = new DemandItem { status = (int)DEMAND_STATUS.EXAMINING, is_delete = (int)DEMAND_ISDELETE.ALIVE };
                        }
                        else
                        {
                            demand = new DemandItem { status = (int)DEMAND_STATUS.POSTED, is_delete = (int)DEMAND_ISDELETE.ALIVE };
                            //SendMessage(int.Parse(demand.member_id), demand.title, "恭喜您发布的" + demand.title + "审核成功");
                        }
                        ApplyDataToDemand(demand);
                        G.DB.Insert<DemandItem>(demand);
                        ResponseJson(new ValueResult { value = demand.status });
                        break;
                    }
                case "draft":
                    {
                        DemandItem demand = new DemandItem { status = (int)DEMAND_STATUS.DRAFT };
                        ApplyDataToDemand(demand);
                        G.DB.Insert<DemandItem>(demand);
                        ResponseJson(new IDResult { id = demand.id });
                        break;
                    }
                case "recycle":
                    {
                        DemandItem demand = G.DB.GetById<DemandItem>(req_id);
                        demand.status = (int)DEMAND_STATUS.RECLAIMED;
                        G.DB.Update<DemandItem>(demand);
                        ResponseJson(new Result());
                        break;
                    }
                case "re_post":
                    {
                        DemandItem demand = G.DB.GetById<DemandItem>(req_id);
                        ApplyDataToDemand(demand);
                        if (FreeValue.GetValue("check.open_check", "1") == "1")
                        {
                            demand.status = (int)DEMAND_STATUS.EXAMINING;
                        }
                        else
                        {
                            demand.status = (int)DEMAND_STATUS.POSTED;
                            //SendMessage(demand.member.id, demand.title, "恭喜您发布的" + demand.title + "审核成功");
                        }
                        G.DB.Update<DemandItem>(demand);
                        ResponseJson(new ValueResult { value = demand.status });
                        break;
                    }
                case "re_draft":
                    {
                        DemandItem demand = G.DB.GetById<DemandItem>(req_id);
                        ApplyDataToDemand(demand);
                        demand.status = (int)DEMAND_STATUS.DRAFT;
                        G.DB.Update<DemandItem>(demand);
                        ResponseJson(new Result());
                        break;
                    }
                case "delete":
                    {
                        if (G.DB.Delete<DemandItem>(req_id) == 0) { ThrowStatus(STATUS.FAILED_DELETE, "删除失败！"); }
                        ResponseJson(new Result());
                        break;
                    }
                case "title_recommend":
                    {
                        string name = GetStringParam(new ReqStringParamOption { Name = "name", Level = REQPARAMLEVEL.FREE });
                        Cd cd = new Cd();
                        Ob ob = new Ob();
                        if (name != "")
                        {
                            cd.And("title like '%{0}%'", name);
                        }
                        cd.And("member_id = {0} and status = 2", UserCode);
                        ob.Desc("id");
                        SqlResult<DemandItem> demandItem = G.DB.Get<DemandItem>(cd.Render(), ob.Render(), 10); //取最近前十条
                        List<DemandItem> demandList = demandItem.GetFirstTableList();

                        SqlResult<ServiceItem> serviceItem = G.DB.Get<ServiceItem>("status = 2");
                        List<ServiceItem> serviceList = serviceItem.GetFirstTableList();

                        StringCompute stringcompute1 = new StringCompute();
                        List<MatchRate> title_list = new List<MatchRate>();
                        List<MatchRate> list = new List<MatchRate>();

                        for (int i = 0; i < demandList.Count; i++)
                        {
                            decimal rate = 0;
                            List<MatchRate> ratelist = new List<MatchRate>();
                            for (int j = 0; j < serviceList.Count; j++)
                            {
                                stringcompute1.SpeedyCompute(serviceList[j].title, demandList[i].title);    // 计算相似度， 不记录比较时间
                                rate = stringcompute1.ComputeResult.Rate;         // 相似度百分之几，完全匹配相似度为1
                                MatchRate match = new MatchRate();
                                match.matchid = demandList[i].id;//当前服务/需求的id
                                match.match_title = demandList[i].title;
                                match.rate = rate;//相似度
                                match.id = serviceList[j].id;//当前服务/需求相似的需求/服务的id
                                match.title = serviceList[j].title;
                                match.datetime = serviceList[j].create_time;
                                match.content = serviceList[j].service_content;//当前服务相似的需求内容
                                match.match_content = demandList[i].demand_content;//当前服务内容
                                ratelist.Add(match);
                            }
                            List<MatchRate> matchList = stringcompute1.MergeSort1(ratelist, 0, ratelist.Count - 1).Take(ratelist.Count < 4 ? ratelist.Count : 4).ToList<MatchRate>(); //获得匹配结果列表,按rate排序
                            title_list.AddRange(matchList);
                        }
                        int current_page = req_current_page;
                        int page_size = req_page_size;
                        int total = title_list.Count;
                        list = (title_list.Skip((current_page - 1) * page_size).Take(page_size).ToList<MatchRate>());
                        ResponseJson(new PageResult<MatchRate> { page = new PageData<MatchRate> { current_page = current_page, page_size = page_size, total = total, list = list } });
                        break;
                    }
                default: break;
            }
        }

        private DemandItem ApplyDataToDemand(DemandItem demand)
        {
            demand.title = req_title;
            demand.member_id = UserCode;
            demand.demand_area = GetStringParam(new ReqStringParamOption { Name = "demand_area" });
            demand.m_type = GetStringParam(new ReqStringParamOption { Name = "m_type" });
            demand.demand_type = GetStringParam(new ReqStringParamOption { Name = "demand_type" });
            demand.demand_content = GetStringParam(new ReqStringParamOption { Name = "demand_content" });
            demand.demand_industry = GetStringParam(new ReqStringParamOption { Name = "demand_industry" });
            demand.demand_beginDate = GetTimeStampParam(new ReqTimeStampParamOption { Name = "demand_beginDate", Level = REQPARAMLEVEL.FREE });
            demand.demand_endDate = GetTimeStampParam(new ReqTimeStampParamOption { Name = "demand_endDate", Level = REQPARAMLEVEL.FREE });
            demand.item_type = GetStringParam(new ReqStringParamOption { Name = "item_type" });
            demand.demand_invest = GetIntParam(new ReqIntParamOption { Name = "demand_invest", Level = REQPARAMLEVEL.FREE, DefaultValue = 0 });
            demand.demand_presentInvest = GetIntParam(new ReqIntParamOption { Name = "demand_presentInvest", Level = REQPARAMLEVEL.FREE, DefaultValue = 0 });
            demand.demand_needInvest = GetIntParam(new ReqIntParamOption { Name = "demand_needInvest", Level = REQPARAMLEVEL.FREE, DefaultValue = 0 });
            demand.demand_use = GetStringParam(new ReqStringParamOption { Name = "demand_use" });
            demand.demand_operation = GetStringParam(new ReqStringParamOption { Name = "demand_operation" });
            demand.demand_diya = GetStringParam(new ReqStringParamOption { Name = "demand_diya" });
            demand.demand_master = GetStringParam(new ReqStringParamOption { Name = "demand_master" });
            demand.demand_tele = GetStringParam(new ReqStringParamOption { Name = "demand_tele" });
            demand.demand_address = GetStringParam(new ReqStringParamOption { Name = "demand_address" });
            demand.appendix_ids = GetStringParam(new ReqStringParamOption { Name = "appendix_id" });
            demand.create_time = DateTimeEx.GetNowTimeStamp();
            demand.number = "dm" + demand.create_time + UserCode;
            demand.demand_remark = GetStringParam(new ReqStringParamOption { Name = "demand_remark" });
            demand.safety_grade = GetIntParam(new ReqIntParamOption { Name = "safety_grade", Level = REQPARAMLEVEL.FREE, DefaultValue = 0 });
            return demand;
        }

    }
    enum DEMAND_STATUS
    {
        DRAFT = 0, // 草稿
        EXAMINING = 1, // 正在审核
        POSTED = 2, // 已发布
        FAILED_EXAMINE = 3, // 审核失败
        RECLAIMED = 4, // 已回收
    }
    enum DEMAND_ISDELETE
    {
        ALIVE = 0,//未删除
        DELETE = 1//已删除
    }
}